package com.xcf.dubboweb.contoller;

import com.xcf.dubbo.service.ServerService;
import com.xcf.dubboweb.interceptor.WebConfiguration;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Semaphore;

@RestController
@RequestMapping("/dubbo")
public class DubboController {

    @Reference
    private ServerService serverService;

    @Autowired
    @Qualifier(WebConfiguration.TASK_EXECUTOR)
    private ThreadPoolTaskExecutor taskExecutor;

    @GetMapping("/ip")
    public String reportIp(@RequestParam String name) {
        String ip = serverService.doIp();
        return "Hello " + name + "! your ip: " + ip;
    }

    @GetMapping("/monitor")
    public void startMonitor() {
        Semaphore semaphore = new Semaphore(2000);
        new Thread(() -> {
            while (true) {
                try {
                    semaphore.acquire();
                    taskExecutor.execute(() -> {
                        try {
                            serverService.methodA();
                            serverService.methodB();
                            serverService.methodC();
                        } finally {
                            semaphore.release();
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
